<template>
  <div>
    <!-- 导航栏组件，添加事件监听 -->
    <NavBar @show-modal="showModal" :user="user" @clean:user="user ={}"/>
    <div class="middle">
      <Carousel/>
      <SearchBox @search="productSearch"/>
      <a href="javascript:void(0)" class="search-more" @click="router.push('/product/search')">更多搜索方式</a>
      <ProductList ref="productListRef"/>
    </div>
    <Footer/>
    <!-- 登录弹窗组件 -->
    <Modal v-if="!user||!user.id" :is-visible="modalConfig.visible" @close-modal="closeModal">
      <Login v-if="1==modalConfig.type" @show-modal="showModal"></Login>
      <Register v-else-if="2==modalConfig.type" @show-modal="showModal"></Register>
      <FindPassword v-else-if="3==modalConfig.type" @show-modal="showModal"></FindPassword>
      <div v-else>
        <span style="color:red">模态框类型错误</span>
      </div>
    </Modal>
  </div>
</template>

<script setup>
import NavBar from '@views/common/NavBar.vue'
import SearchBox from '@views/product/SearchBox.vue'
import Carousel from '@/views/home/Carousel.vue'
import ProductList from '@/views/home/ProductList.vue'
import Footer from '@views/common/Footer.vue'
import Modal from '@/views/common/Modal.vue'
import Login from '@/views/Login.vue'
import FindPassword from '@/views/FindPassword.vue'
import Register from '@/views/Register.vue'
import {reactive, ref, onMounted, onUnmounted} from 'vue';
import {ElMessage} from 'element-plus'
import apis from "@/config/api-config.js";
import getResponse from "@assets/js/http-client.js";
import {IMG_BASE_PATH} from "@/config/api-config.js";
import {useRouter, useRoute} from "vue-router";

const router = useRouter();
const route = useRoute();
//会员用户
const user = ref({});
//商品列表组件引用
const productListRef = ref(null);
//模态框信息
const modalConfig = reactive({
  visible: false,
  //1:显示会员登录模态框;2:显示会员注册模态框;3:显示找回密码或忘记密码模态框
  type: 1
});
//关闭模态框
const closeModal = () => {
  modalConfig.visible = false;
  modalConfig.type = 1;//默认显示登录模态框
}
//打开模态框
const showModal = (type) => {
  if (!(1 === type || 2 === type || 3 === type || 0 === type)) {
    ElMessage({
      message: '打开模态框失败,未知的页面',
      type: 'error',
      duration: 2000
    });
    return;
  }
  //0表示登录成功后,关闭登录框
  if (0 === type) {
    closeModal();
    getUserInfo();
    return;
  }
  modalConfig.type = type;
  modalConfig.visible = true;
}
onMounted(async () => {
  //注册window对象scroll事件
  window.addEventListener('scroll', handleScroll)
  await getUserInfo();
  if (user && user.id) {
    return;
  }
  // 检查路由参数是否需要显示登录框
  if (route.query.model === '1') {
    showModal(1);
  }
});
/**
 * 获取会员用户信息
 * @returns {Promise<void>}
 */
const getUserInfo = async () => {
  let token = localStorage.getItem('wemall-token');
  if (token === null) {
    return;
  }
  //如果有token,说明已登录过系统,则根据token获取用户数据
  let url = apis.member.getInfo.url;
  let type = apis.member.getInfo.type;
  //token参数已统一处理,无需再手动添加
  const result = await getResponse(url, type);
  if (200 !== result.code) {
    console.info('获取用户信息失败:', result.message);
    return;
  }
  //console.info('获取用户信息成功:', result.data);
  user.value = result.data;
  let avatar = user.value.avatar;
  if (!avatar) {
    user.value.avatar = 'src/assets/img/member/user_center.png';
  } else {
    user.value.avatar = IMG_BASE_PATH + avatar;
  }
}
/**
 * 根据关键字搜索商品
 * @param keyword
 */
const productSearch = (keyword) => {
  productListRef.value.fetchProducts(true, keyword);
}

// 添加滚动事件处理函数
const handleScroll = () => {
  // 获取滚动高度、窗口高度和文档总高度
  const scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
  const windowHeight = document.documentElement.clientHeight || document.body.clientHeight;
  const documentHeight = getPageHeight();

  // 判断是否滚动到页面底部
  if (scrollTop + windowHeight >= documentHeight - 10) {
    //查询下一页数据
    productListRef.value.fetchProducts(false, '');
  }
};
const getPageHeight = () => {
  // 兼容不同浏览器的文档高度计算方式
  const bodyHeight = document.body.offsetHeight;
  const htmlHeight = document.documentElement.offsetHeight;
  // 返回最大高度值作为网页总高度
  return Math.max(bodyHeight, htmlHeight);
};
// 添加组件卸载时的事件移除
onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll);
});
</script>

<style>
/* 全局样式 */
.middle {
  margin: 0 auto;
  max-width: 1200px;
  width: 100%;
  padding: 0 20px;
}

.search-more {
  position: relative;
  float: right;
  bottom: 40px;
  right: 240px;
  display: inline-block;
  color: #666;

}
</style>